<?php


namespace App\Rpc\client\impl;

use App\Common\Res;
use App\Common\StringUtils;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\NumberRecord;
use App\Model\Seller;
use App\Request\client\NumberRecordRequest;
use App\Rpc\client\NumberRecordInterface;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface;


class NumberRecordImpl implements NumberRecordInterface
{
    use StringUtils, Res;

    /**
     * 新增设备操作记录
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function add(array $params): array
    {
        ApplicationContext::getContainer()->get(NumberRecordRequest::class)->validated($params, __FUNCTION__);
        $seller = Context::get(ServerRequestInterface::class)->getAttribute('seller');
        if (empty($seller))
            return $this->Error(ErrorCode::ERROR, "请登录");
        $sellerArr = json_decode($seller, true);
        return Db::transaction(function () use ($params, $sellerArr) {
            $numberRecord = NumberRecord::create([
                'code_number' => $params['code_number'],
                'host_name' => $params['host_name'],
                'company' => $params['company'],
                'today_date' => $params['today_date'],
                'today_time' => $params['today_time'],
                'action_type' => $params['action_type'],
                'create_time' => time(),
                'seller_id' => $sellerArr['id'],
            ]);
            if (!empty($numberRecord)) {
                if (trim($params['action_type']) == 'recovery_success') {
                    $sellerInfo = Seller::where(['id' => $sellerArr['id']])->first();
                    $sellerInfo->balance = $sellerInfo['balance'] - 1 >= 0 ? $sellerInfo['balance'] - 1 : 0;
                    $sellerInfo->save();
                }
                return $this->Success('新增成功');
            }
            return $this->Error(ErrorCode::ERROR, "新增失败");
        });
    }
}